﻿ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ICU;
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebSocket4Net;
using Path = System.IO.Path;

namespace Chat
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        WebSocket webSocket;
        string host = Resource1.ServerHostV6;
        long id = 0;
        string nowid = "u1";
        Dictionary<string, long> unreadCount = new Dictionary<string, long>();
        Dictionary<string, Message> lastMessage = new Dictionary<string, Message>();
        LocalMessageContainer messageContainer;
        private void AddMessageAreaContent(Message message)
        {
            if (Thread.CurrentThread == MessageArea.Dispatcher.Thread)
            {
                if (message.sender == id)
                    MessageArea.Children.Add(new UserControlMessageSent(message.msg, message.sendTime));
                else
                    MessageArea.Children.Add(new UserControlMessageReceived(message.msg, message.sendTime));
            }
            else
            {
                MessageArea.Dispatcher.Invoke(new Action<Message>(AddMessageAreaContent), message);
            }
        }
        public MainWindow()
        {
#if DEBUG
            host = Resource1.DebugHost;
#endif
            if (!Directory.Exists(Path.Combine(id.ToString(), "message"))) Directory.CreateDirectory(Path.Combine(id.ToString(), "message"));
            if (!Directory.Exists(Path.Combine(id.ToString(), "logs"))) Directory.CreateDirectory(Path.Combine(id.ToString(), "logs"));
            if (!Directory.Exists(Path.Combine(id.ToString(), "face"))) Directory.CreateDirectory(Path.Combine(id.ToString(), "face"));
            if (!File.Exists(Path.Combine(id.ToString(), "contract"))) File.Create(Path.Combine(id.ToString(), "contract"));
            InitializeComponent();
            //context.Children.Add(new UserControlMessageReceived());
            this.Header.MouseLeftButtonDown += (o, e) => { DragMove(); };
            Login login = new Login(host);
            try
            {
                login.ShowDialog();
            }
            catch (Exception ex)
            {

            }
            id = login.id;
            messageContainer = new LocalMessageContainer(id);
            webSocket = login.webSocket;
            webSocket.MessageReceived += ReceiveMessage;
            webSocket.MessageReceived += BasicInfoListener;
            webSocket.AutoSendPingInterval = 1000;
        }

        private void BasicInfoListener(object sender, MessageReceivedEventArgs e)
        {
            Protocol protocol = new Protocol(e.Message);
            if (protocol.Method == "Search")
            {

            }
        }

        //Dictionary<long, List<List<IUserControlMessage>>> m;


        private void ReceiveMessage(object sender, MessageReceivedEventArgs e)
        {
            if (e.Message[..e.Message.IndexOf('\n')] == "Receive")
            {
                Message message = JsonConvert.DeserializeObject<ICU.Message>(e.Message[(e.Message.IndexOf("\n\n") + 2)..]);
                if (message.sender == id)
                {
                    
                }
                messageContainer.AddMessage(message.messageId, message);
                AddMessageAreaContent(message);
            }
            
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("确定要退出吗", "提示", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                Method.LogoutExit(webSocket);
            }
        }

        private void Select(UserOverviewItem overviewItem)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.IsEnabled = false;
            CurrentContractName.Text = "正在同步消息...";
            long last = 0;
            webSocket.Send($"Receive\n\n{LocalMessageContainer.GetLastId(id)}");
            Task.Delay(100).Wait();
            webSocket.Send($"Search\n\n{new JObject { { "type", "groups" }, { "target", 0 } }}");
            webSocket.Send($"Search\n\n{new JObject { { "type", "face" }, { "target", id } }}");
            CurrentContractName.Text = "已完成";
            Task.Delay(500).Wait();
            this.IsEnabled = true;
        }

        private void SendFile_Click(object sender, RoutedEventArgs e)
        {
            if (nowid == "u0")
            {
                MessageBox.Show("请先在左边选择聊天对象！");
                return;
            }
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文件|*.*";
            openFileDialog.ShowDialog();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (nowid == "u0")
            {
                MessageBox.Show("请先在左边选择聊天对象！");
                return;
            }
            webSocket.Send($"Send\n\n{new JObject { { "isGroup", nowid[0] == 'g' }, { "msg", MessageContext.Text }, { "target", Convert.ToInt64(nowid[1..]) }, { "isReply", false }, { "replyId", 0 } }.ToString(Formatting.None)}");
            MessageContext.Text = "";
        }
    }
}
